package com.honghu.villagepost.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import com.honghu.villagepost.R
import com.honghu.villagepost.adapter.SearchItemAdapter
import com.honghu.villagepost.base.BaseActivity
import com.honghu.villagepost.constant.Constants
import com.tencent.lbssearch.TencentSearch
import com.tencent.lbssearch.`object`.param.SuggestionParam
import com.tencent.lbssearch.`object`.result.SuggestionResultObject
import com.tencent.lbssearch.httpresponse.BaseObject
import com.tencent.lbssearch.httpresponse.HttpResponseListener
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
import kotlinx.android.synthetic.main.activity_search_addr.*
import org.greenrobot.eventbus.EventBus
import java.lang.ref.WeakReference

/**
 * @author: mqwang
 * @create: 3/9/21 8:15 AM
 * @Description: 定位地址搜索
 */
class SearchAddrActivity : BaseActivity(), TencentLocationListener {


    private var selectItem: SuggestionResultObject.SuggestionData? = null
    private val searchItemAdapter : SearchItemAdapter by lazy {
        SearchItemAdapter()
    }

    private var city: String? = ""
    private val MSG_SUGGESTION = 10000

    private val handler: MyHandler = MyHandler(this)

    companion object {
        fun self(context: Context, string: String, city: String) {
            val intent = Intent(context, SearchAddrActivity::class.java)
            intent.putExtra(Constants.CONTENT, string)
            intent.putExtra(Constants.CITY, city)
            context.startActivity(intent)
        }
    }

    private class MyHandler(activity: SearchAddrActivity) : Handler() {
        private val mActivity: WeakReference<SearchAddrActivity>
        override fun handleMessage(msg: Message) {
            // TODO Auto-generated method stub
            val activity: SearchAddrActivity? = mActivity.get()
            if (activity != null) {
                activity.handleMessage(msg)
            }
        }

        init {
            mActivity = WeakReference<SearchAddrActivity>(activity)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_search_addr
    }

    override fun isNeedTitleBar(): Boolean {
        return false
    }


    override fun init(savedInstanceState: Bundle?, container: View?) {

        etSearch.addTextChangedListener(textWatcher)
        etSearch.setOnFocusChangeListener(View.OnFocusChangeListener { v, hasFocus -> // TODO Auto-generated method stub
            if (!etSearch.hasFocus()) {
            }
        })

        tv_confirm.setOnClickListener {
            EventBus.getDefault().post(selectItem)
            finish()
        }

        var content = intent.getStringExtra(Constants.CONTENT)
        city = intent.getStringExtra(Constants.CITY)
        etSearch.setText(content)


        recycler_view.adapter = searchItemAdapter
        searchItemAdapter.setOnItemClickListener { adapter, view, position ->
            selectItem = adapter.data.get(position) as SuggestionResultObject.SuggestionData?
            etSearch.setText(selectItem!!.address)
        }

    }

    val textWatcher: TextWatcher = object : TextWatcher {
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            // TODO Auto-generated method stub
            suggestion(s.toString())

        }

        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int,
                                       after: Int) {
        }

        override fun afterTextChanged(s: Editable) {
        }
    }

    /**
     * 关键字提示
     * @param keyword
     */
    protected fun suggestion(keyword: String) {
        if (TextUtils.isEmpty(keyword)) {
            return
        }
        val tencentSearch = TencentSearch(this)
        val suggestionParam = SuggestionParam(keyword, city)

        //suggestion也提供了filter()方法和region方法
        //具体说明见文档，或者官网的webservice对应接口
        tencentSearch!!.suggestion(suggestionParam, object : HttpResponseListener<BaseObject?> {
            override fun onFailure(arg0: Int, arg1: String, arg2: Throwable) {
                //printResult(arg1);
            }

            override fun onSuccess(p0: Int, arg1: BaseObject?) {
                val msg = Message()
                msg.what = MSG_SUGGESTION
                msg.obj = arg1
                handler.sendMessage(msg)
            }
        })
    }

    fun handleMessage(msg: Message) {
        when (msg.what) {
            MSG_SUGGESTION -> {
                searchItemAdapter.setNewData((msg.obj as SuggestionResultObject).data)
            }
            else -> {

            }
        }
    }


    override fun onLocationChanged(p0: TencentLocation?, p1: Int, p2: String?) {
    }

    override fun onStatusUpdate(p0: String?, p1: Int, p2: String?) {
    }
}